/**
 * Copyright (c) 2002-2012 旭鸣信息
 * All rights reserved. 
 * File：WebCounterListener.java
 * History: Nov 14, 2013: Initially created, liuzhi.
 */
package com.xteam.ecsystem.utils;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.xteam.ecsystem.dao.IWelcomeDao;
import com.xteam.ecsystem.entities.BaseWebCounter;

/**
 * 网站浏览量统计过滤器
 * @author liuzhi
 *
 */
public class WebCounterFilter implements Filter{
	
	private IWelcomeDao welDao;
	
	/**
	 * @return 属性welDao的值.
	 */
	public IWelcomeDao getWelDao() {
		return this.welDao;
	}

	/**
	 * @param welDao 属性welDao.
	 */
	public void setWelDao(IWelcomeDao welDao) {
		this.welDao = welDao;
	}

	@Override
	public void destroy() {
		System.out.println("=============== WebCounterFilter destroy ============");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		String reqUrl = request.getRequestURL().toString();
		String remoteIp = request.getRemoteAddr();
		
		WebCounterSingleton instance = WebCounterSingleton.getInstance();
		Calendar c = Calendar.getInstance();
		
		BaseWebCounter webCounter = new BaseWebCounter();
		webCounter.setBwcYear(c.get(Calendar.YEAR));
		webCounter.setBwcMonth(c.get(Calendar.MONTH) + 1);
		webCounter.setBwcDate(c.get(Calendar.DATE));
		webCounter.setBwcHour(c.get(Calendar.HOUR_OF_DAY));
		webCounter.setBwcMinute(c.get(Calendar.MINUTE));
		webCounter.setBwcFrompage(instance.getFromPage());
		webCounter.setBwcTopage(reqUrl);
		webCounter.setBwcIp(remoteIp);
		
		this.welDao.savePageViews(webCounter);
		
		instance.setFromPage(reqUrl);
		
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("=============== WebCounterFilter init ============");
	}
	
	
	
	
	
	
	
	
	
	

}
